# -*- coding: utf-8 -*-
class StoreController < ApplicationController

 # before_filter :login_required, :except=> [ :indexg]

  def index
    @products = Product.find_products_for_sale
    @cart = find_cart
    @grind = Grindselect.find(:all)
  end

  def show
    @product = Product.find(params[:id])
    @cart = find_cart
    @grind = Grindselect.find(:all)
  end

  #adds selected items to the cart
  def add_to_cart
    begin
      product = Product.find(params[:id])
      quantity = Integer(params['quantity'])
      price = Integer(params['baglist'])
      grind = params['selected_grind']
      name = params[:title]
    end
  end
  #empties all items from the cart
  def empty_cart
    session[:cart] = nil
    redirect_to_index
  end

  #removess item from the cart
  def remove_item
    product = Product.find(params[:id])

    rescue ActiveRecord::RecordNotFound
        logger.error("구입 불가능한 아이템 #{params[:id]}")
        redirect_to_index("구입 불가능한 아이템입니다.")
    else
      @cart = find_cart
      @cart.remove_product(product)

       respond_to do |format|
       format.js if request.xhr?
       format.html {redirect_to_index}
    end
  end

private

  def redirect_to_index(msg = nil)
    flash[:notice] = msg if msg
    redirect_to :action => 'index'
  end


  def find_cart
    session[:cart] ||= Cart.new
  end


end

